package com.jiang.smartdangjian.tool;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public abstract class MyCallback implements Callback {
    private static String TAG = "MyCallback";

    Activity activity;
    Class clz;

    public MyCallback(Activity activity, Class clz) {
        this.activity = activity;
        this.clz = clz;
    }

    @Override
    public void onFailure(Call call, IOException e) {
        activity.runOnUiThread(() -> {
            Log.e(TAG, "onFailure: " + e.getLocalizedMessage(), e);
            Toast.makeText(activity, e.getMessage(), Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String string = response.body().string();
        activity.runOnUiThread(() -> {
            try {
                Log.d(TAG, "onResponse: " + string);
                onFinish(HttpUtil.GSON.fromJson(string, clz));
            } catch (Exception e) {
                Log.e(TAG, "onResponse: " + e.getLocalizedMessage(), e);
                Toast.makeText(activity, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public abstract void onFinish(Object obj);
}
